package com.haorui.lygyd.wxapi.service;

import com.haorui.base.core.model.Search;
import com.haorui.base.core.service.BaseService;
import com.haorui.lygyd.wxapi.entity.WXUserInfoEntity;
import com.haorui.lygyd.wxapi.repository.WXUserInfoRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 系统生成
 * 日期: Sat Sep 30 16:00:14 CST 2017
 */
@Service
@Slf4j
public class WXUserInfoService extends BaseService<WXUserInfoEntity,String> {
    private WXUserInfoRepository weixinUserInfoRepository;
    public WXUserInfoService(@Autowired WXUserInfoRepository weixinUserInfoRepository) {
        super(weixinUserInfoRepository);
        this.weixinUserInfoRepository=weixinUserInfoRepository;
    }

    @Override
    protected Search<WXUserInfoEntity> getSearch() {
        return new Search<WXUserInfoEntity>(WXUserInfoEntity.class);
    }

    public WXUserInfoEntity wxgetweixinUserByOpenId(String openId)
    {
        return weixinUserInfoRepository.findByOpenId(openId);
    }
    @Transactional(rollbackFor = Exception.class)
    public WXUserInfoEntity wxgetweixinUserByMemberId(String openId, String memberId)
    {
        if(openId==null || memberId==null){
            return null;
        }
        WXUserInfoEntity weixinUserInfoEntity=weixinUserInfoRepository.findByOpenId(openId);
        if(weixinUserInfoEntity!=null && weixinUserInfoEntity.getMemberId()==null){
            log.info("微信用户未绑定会员，系统自动绑定会员，会员号为："+memberId);
            weixinUserInfoEntity.setMemberId(memberId);
            weixinUserInfoRepository.save(weixinUserInfoEntity);
        }

        return weixinUserInfoEntity;
    }
    public List<WXUserInfoEntity> findUserInfoBymemberId(String memberId){
        return weixinUserInfoRepository.findAllByMemberId(memberId);
    }

}
